package com.ktgj.common.core.utils.helper;

import java.util.List;
import java.io.File;
import java.util.ArrayList;

public class PathHelper
{
	public static String combine(String... paths)
	{
		StringBuilder sbd = new StringBuilder();
		for (String path : paths)
		{
			if (path == null || path.isEmpty())
			{
				continue;
			}

			if (path.startsWith("/") || path.startsWith("\\"))
			{
				sbd.append(path);
			} else
			{
				sbd.append("/").append(path);
			}

			char last = sbd.charAt(sbd.length() - 1);
			if (last == '/' || last == '\\')
			{
				sbd.setLength(sbd.length() - 1);
			}
		}

		return sbd.toString();
	}

	public static List<String> getAllFilenames(String dir, String rel)
	{
		File directory = new File(dir);
		List<String> files = new ArrayList<>();
		for (File file : directory.listFiles())
		{
			if (file.isDirectory())
			{
				List<String> subFiles = getAllFilenames(file.getAbsolutePath(), rel);
				if (subFiles != null && subFiles.size() > 0)
				{
					files.addAll(subFiles);
				}
			} else
			{
				String relPath = getRelativePath(rel, file.getPath());
				files.add(relPath);
			}
		}

		return files;
	}

	public static String getRelativePath(String accord, String path)
	{
		if (accord == null || accord.isEmpty() || path == null || path.isEmpty())
		{
			return path;
		}

		int index = path.indexOf(accord);
		if (index == -1)
			return "";

		String rel = path.substring(index + accord.length());
		if (rel.length() == 0)
		{
			return path;
		}

		if (rel.startsWith("\\") || rel.startsWith("/"))
		{
			rel = rel.substring(1);
		}

		return rel;
	}

	public static String getExtension(String fileName)
	{
		if (StringHelper.isNullOrEmpty(fileName))
			return "";
		int index = fileName.lastIndexOf(".");
		if (index == -1)
			return "";
		return fileName.substring(index);
	}
}
